<template>
  <div class="systemMessagePush">
    <el-card shadow="hover">
      <div class="searchBox">
        <div class="oneBox">
          <el-input placeholder="请输入ID" v-model="id">
            <template slot="prepend">ID</template>
          </el-input>
          <el-input placeholder="请输入内容" v-model="content">
            <template slot="prepend">内容</template>
          </el-input>
          <el-button class="btn" @click="systemMessageBth">查找搜索</el-button>
        </div>
        <div class="addBox">
          <el-button class="btn" @click="dialogVisible = true"
            >新增推送</el-button
          >
        </div>
      </div>
      <el-radio-group v-model="index" fill="#39383d" @change="systemMessageBth">
        <el-radio-button label="1">未发送</el-radio-button>
        <el-radio-button label="2">已发送</el-radio-button>
      </el-radio-group>
      <div style="height: 10px"></div>
      <!-- <div class="p">
        <p :class="{ active: index == 1 }" @click="activeStatusA()">未发送</p>
        <p :class="{ active: index == 2 }" @click="activeStatusB()">已发送</p>
      </div> -->

      <!-- 未发送 -->
      <div>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="ID" width="50"> </el-table-column>
          <el-table-column prop="pushType" width="80" label="发布类型">
            <template slot-scope="scoped">
              {{ pushType(scoped.row.pushType) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="content"
            label="内容"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="pushTime" label="投送时间"> </el-table-column>
          <el-table-column prop="state" width="80" label="投送状态">
            <template slot-scope="scoped">
              {{ state(scoped.row.state) }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="投送用户">
            <template slot-scope="scoped">
              {{ userType(scoped.row.type) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="province"
            label="地域选择"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scoped">
              {{ scoped.row.province ? city(scoped.row.province) : "" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="mood"
            label="心情选择"
            :show-overflow-tooltip="true"
          >
            <!-- <template slot-scope="scoped">
              {{ scoped.row.province ? city(scoped.row.province) : "" }}
            </template> -->
          </el-table-column>
          <el-table-column prop="images" label="附件">
            <template slot-scope="scoped">
              <!-- {{ scoped.row.province ? city(scoped.row.province) : "" }} -->
              <el-image
                v-if="scoped.row.images && scoped.row.images[0] != ''"
                style="width: 50px; height: 50px"
                :src="scoped.row.images[0]"
                :preview-src-list="[scoped.row.images]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="link"
            label="链接"
            :show-overflow-tooltip="true"
          >
            <!-- <template slot-scope="scoped">
              {{ scoped.row.province ? city(scoped.row.province) : "" }}
            </template> -->
          </el-table-column>
          <el-table-column
            fixed="right"
            width="200"
            prop=""
            label="操作"
            v-if="index == 1"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="info"
                plain
                @click="withdrawBtn(scope.row)"
                >撤回</el-button
              >
              <el-button
                size="mini"
                type="success"
                plain
                @click="sendNowBtn(scope.row)"
                >立即发送</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="page"
          :limit.sync="pageSize"
          @pagination="getList"
        />
      </div>

      <!-- 已发送 -->
      <!-- <div v-if="index == 2">
        <el-table :data="tableDataA" style="width: 100%">
          <el-table-column prop="date" label="ID"> </el-table-column>
          <el-table-column prop="name" label="标题"> </el-table-column>
          <el-table-column prop="address" label="内容"> </el-table-column>
          <el-table-column prop="address" label="投送时间"> </el-table-column>
          <el-table-column prop="address" label="投送状态"> </el-table-column>
          <el-table-column prop="address" label="投送用户"> </el-table-column>
          <el-table-column prop="address" label="地域选择"> </el-table-column>
        </el-table>
        <pagination
          v-show="totalA > 0"
          :total="totalA"
          :page.sync="pageA"
          :limit.sync="pageSizeA"
          @pagination="getListA"
        />
      </div> -->

      <!-- 新增推送弹框 -->
      <el-dialog
        title="系统消息发布"
        :visible.sync="dialogVisible"
        width="50%"
        style="margin-top: -12vh"
        @close="close"
      >
        <el-form :model="form" :rules="rules" ref="form">
          <div>
            <el-form-item label="发布消息类型" prop="bizType">
              <el-select
                v-model="form.bizType"
                size="small"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <p>
                <el-input
                  v-model="form.title"
                  placeholder="请输入标题"
                ></el-input>
              </p>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <p>
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="form.content"
                >
                </el-input>
              </p>
            </el-form-item>
            <p>
              <el-form-item label="投放用户" prop="user_type">
                <el-radio-group v-model="form.user_type">
                  <el-radio label="0">所有用户</el-radio>
                  <el-radio label="1">男用户</el-radio>
                  <el-radio label="2">女用户</el-radio>
                  <el-radio label="3">其他性别用户</el-radio>
                  <el-radio label="4">指定用户</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="userId">
                <el-input
                  placeholder="请输入用户ID"
                  v-model="form.userId"
                  v-if="form.user_type == 4"
                >
                  <template slot="prepend">用户ID</template>
                </el-input>
              </el-form-item>
            </p>
            <el-collapse v-model="activeNames" accordion>
              <el-collapse-item name="1">
                <template slot="title">
                  <span class="txt">投放精准用户</span>
                </template>
                <p>
                  <el-form-item prop="area">
                    <span class="area">地区选择</span>
                    <el-cascader
                      class="cascader"
                      size="mini"
                      @change="change"
                      v-model="form.area"
                      :options="options"
                      :props="props"
                      clearable
                      :collapse-tags="true"
                      :filterable="true"
                    ></el-cascader>
                  </el-form-item>
                </p>
                <p>
                  <el-form-item prop="moodId">
                    <span>心情选择</span>
                    <el-select
                      class="select"
                      v-model="form.moodId"
                      multiple
                      collapse-tags
                      size="small"
                      style="margin-left: 20px"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in options1"
                        :key="item.id"
                        :label="item.content"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </p>
              </el-collapse-item>
            </el-collapse>

            <el-form-item label="推送时间" prop="pushType">
              <el-radio-group v-model="form.pushType">
                <el-radio label="1">立即发送</el-radio>
                <el-radio label="2">定时发送</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择推送时间" prop="pushTime">
              <el-date-picker
                size="mini"
                v-model="form.pushTime"
                :disabled="form.pushType == 1"
                :picker-options="pickerOptions1"
                type="datetime"
                placeholder="选择日期时间"
                default-time="12:00:00"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <p>
              <el-form-item label="添加图片" prop="img">
                <el-upload
                  class="avatar-uploader"
                  :http-request="upLoad"
                  :on-preview="handlePictureCardPreview"
                  :on-success="handleAvatarSuccess"
                  :show-file-list="false"
                  action
                >
                  <img
                    v-if="form.dialogImageUrl"
                    :src="form.dialogImageUrl"
                    class="avatar"
                    style="width: 200px; height: 180px"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </p>
            <el-form-item label="添加链接" prop="url">
              <el-input placeholder="请输入内容" v-model="form.url">
                <template slot="prepend">网址</template>
              </el-input>
            </el-form-item>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import {
  noticeList,
  noticeAdd,
  noticeDel,
  noticeSend,
} from "@/api/operationManagement";
// import { provinceAndCityData, CodeToText } from "element-china-area-data";
// import { cityOptions } from "@/assets/city";
import { moodandintendList } from "@/api/operationManagement";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
import axios from "axios";
export default {
  components: { Pagination },
  inject: ["reload"],
  data() {
    return {
      index: "1",
      dialogVisible: false, //新增推送弹框

      id: "",
      content: "", //内容
      activeNames: ["1"],
      //未发送
      tableData: [
        {
          date: "2016-05-2111",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
      ],
      total: 0,
      page: 1, //页码
      pageSize: 10, //每页条数

      //已发送
      tableDataA: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
      ],
      totalA: 0,
      pageA: 1, //页码
      pageSizeA: 10, //每页条数

      //弹框
      form: {
        title: "",
        content: "",
        user_type: [],
        userId: "",
        area: [],
        province: [], //地区
        moodId: "", //心情id
        pushType: "",
        pushTime: "",
        dialogImageUrl: "",
        img: "",
        url: "",
        bizType: "",
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
        user_type: [
          { required: true, message: "请选择投放用户", trigger: "change" },
        ],
        bizType: [
          { required: true, message: "请选择消息类型", trigger: "change" },
        ],
        pushType: [
          { required: true, message: "请选择推送时间", trigger: "change" },
        ],
      },
      props: { multiple: true },
      options: [],
      options1: [],
      options2: [
        { label: "用户引导", value: 1 },
        { label: "活动链接", value: 2 },
        { label: "违规通知", value: 3 },
        { label: "反馈结果", value: 4 },
        // { label: "评论想法", value: 5 },
        // { label: "转发想法", value: 6 },
        // { label: "点赞想法", value: 7 },
        { label: "其他", value: 0 },
      ],
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      radio: "1",
      value3: "",
      dialogImageUrl: "",
      mapUrl:
        "https://restapi.amap.com/v3/config/district?keywords=&subdistrict=2&extensions=base&key=1fb6fec107d73af4078cb7772783e018",
    };
  },
  methods: {
    //系统消息查找搜索
    systemMessageBth() {
      this.page = 1;
      this.getList();
    },
    //未发送 撤回按钮
    withdrawBtn(obj) {
      this.$confirm("是否撤回?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          noticeDel({ id: obj.id }).then((res) => {
            if (res.code == 0) {
              this.$message({ type: "success", message: "撤回成功！" });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //未发送 立即发送按钮
    sendNowBtn(obj) {
      this.$confirm("是否立即发送?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          noticeSend({ id: obj.id }).then((res) => {
            if (res.code == 0) {
              this.$message({ type: "success", message: "发送成功！" });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //未发送tab
    activeStatusA() {
      this.index = 1;
    },
    submit() {
      this.$refs.form.validate((res) => {
        if (res) {
          let obj = JSON.parse(JSON.stringify(this.form));
          delete obj.area;
          delete obj.dialogImageUrl;
          if (obj.user_type == 4 && obj.userId == "") {
            this.$message({
              type: "error",
              message: " 指定用户id不能为空！",
            });
            return;
          }
          noticeAdd(obj).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "添加成功！",
              });
              this.dialogVisible = false;
              this.getList();
            } else {
              this.$message.error("添加失败，请重试!");
            }
          });
        }
      });
    },
    close() {
      this.$refs.form.resetFields();
      this.form.dialogImageUrl = "";
      this.form.area = [];
      this.form.province = [];
      this.form.bizType = "";
    },
    //获取列表
    async getList() {
      const res = await noticeList({
        type: this.index,
        id: this.id,
        content: this.content,
        page: this.page,
        pageSize: this.pageSize,
      });
      if (res.code == 0) {
        this.total = res.data.count;
        this.tableData = res.data.list;
      }
    },
    //已发送tab
    activeStatusB() {
      this.index = 2;
    },
    change(value) {
      console.log(value);
      let area = [];
      value.forEach((item) => {
        area.push(item.join(","));
      });
      // // const area = CodeToText[("110000", "110100")];
      this.form.province = area;
    },

    handleAvatarSuccess(res, file) {
      this.form.dialogImageUrl = URL.createObjectURL(file.raw);
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date()),
        // fileNames = "/img/" + file.file.name;
        fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      console.log(fileNames);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          this.form.img = fileNames;
          //下面是如果对返回结果再进行处理，根据项目需要
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    handlePictureCardPreview(file) {
      this.form.dialogImageUrl = file.url;
    },
    //获取心情列表
    async getMoodandintendList() {
      const res = await moodandintendList({ type: 1, pageSize: 100, page: 1 });
      if (res.code == 0) {
        console.log(res);
        this.options1 = res.data.list;
      }
    },
  },
  created() {
    axios.get(this.mapUrl).then((res) => {
      console.log(res);
      let arr = [];
      // res.data.districts[0].districts.forEach(item=>{

      // })
      const getTree = (mapArr, arr) => {
        mapArr.forEach((item, index) => {
          arr.push({ value: item.name, label: item.name });
          if (item.districts.length != 0) {
            arr[index].children = [];
            getTree(item.districts, arr[index].children);
          }
        });
      };
      getTree(res.data.districts[0].districts, arr);
      arr.forEach((item) => {
        if (item.value == "北京市") {
          item.children = [
            {
              value: "北京市",
              label: "北京市",
            },
          ];
        }
        if (item.value == "天津市") {
          item.children = [
            {
              value: "天津市",
              label: "天津市",
            },
          ];
        }
        if (item.value == "上海市") {
          item.children = [
            {
              value: "上海市",
              label: "上海市",
            },
          ];
        }
        if (item.value == "重庆市") {
          item.children = [
            {
              value: "重庆市",
              label: "重庆市",
            },
          ];
        }
      });
      this.options = arr;
    });
    this.getList();
    this.getMoodandintendList();
  },
  computed: {
    pushType() {
      return (value) => {
        switch (value) {
          case "1":
            return "用户引导";
          case "2":
            return "活动链接";
          case "3":
            return "违规通知";
          case "4":
            return "反馈结果";
          case "5":
            return "评论想法";
          case "6":
            return "转发想法";
          case "7":
            return "点赞想法";
          case "0":
            return "其他";
        }
      };
    },
    state() {
      return (value) => {
        switch (value) {
          case 1:
            return "待推送";
          case 5:
            return "已推送";
          case 10:
            return "已撤销";
        }
      };
    },
    userType() {
      return (value) => {
        switch (value) {
          case "0":
            return "全部用户";
          case "1":
            return "男用户";
          case "2":
            return "女用户";
          case "3":
            return "其他用户";
          case "4":
            return "指定用户";
        }
      };
    },
    city() {
      return (val) => {
        let city = "";
        val.forEach((item, index) => {
          city += item.city;
          if (index != val.length - 1) {
            city += ",";
          }
        });
        return city;
      };
    },
  },
};
</script>

<style lang="less">
.systemMessagePush {
  margin: 30px;
  height: 100%;
  .searchBox {
    display: flex;
    margin-bottom: 20px;
    .oneBox {
      display: flex;
      width: 50%;
      .el-input {
        margin-right: 20px;
        width: 260px;
      }
    }
    .addBox {
      display: flex;
      justify-content: flex-end;
      flex: 1;
    }
  }
  .p {
    display: flex;
    p {
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
    }
    .active {
      background-color: #ec6564;
      color: #fff;
      border-radius: 10px;
    }
  }
  .el-dialog {
    p {
      margin: 0 !important;
      .span {
        margin-bottom: 10px;
        display: inline-block;
      }
      .el-checkbox {
        margin: 0px 10px;
      }
      .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 80px;
        text-align: center;
      }
      .avatar {
        width: 80px;
        height: 80px;
        display: block;
      }
    }
  }
  .area {
    margin-right: 20px;
  }
  .el-collapse {
    border: none;
  }
  .el-collapse-item__header {
    border-bottom: none;
  }
  .cascader {
    width: 300px;
  }
  .select {
    width: 300px;
  }
  .txt {
    color: #606266 !important;
    font-size: 14px !important;
    font-weight: 700 !important;
  }
}
</style>